package com.kun.permiss.config;

import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.io.Serializable;
import java.util.Collection;

/**
 * @author fangkun
 * @create 2023-05-15-10:43
 *
 * @PreAuthorize("hasPermission('/add','system:user:add')")：需要定义权限评估器
 *
 * @PreAuthorize("hasAuthority('system:user:add')")：不需要自己定义权限评估器
 *
 * 自定义的权限评估器
 * 只需要将这个自定义的权限评估器注册到 Spring 容器，它就会自动生效
 */
//@Component
public class CustomPermissionEvaluator implements PermissionEvaluator {
    @Override
    public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        /*
         * 字符串匹配方式
         * for (GrantedAuthority authority : authorities) {
         *     if (authority.getAuthority().equals(permission)){
         *         return true;
         *     }
         * }
         */
        /**
         * system.user.*
         *
         * AntPathMatcher antPathMatcher = new AntPathMatcher();
         *
         * 如果想要通配符，可以使用antPathMatchar
         * if (antPathMatcher.match(authority.getAuthority(), (String) permission)) {
         *        //说明当前登录的用户具备当前访问所需要的权限
         *        return true;
         *  }
         */

        AntPathMatcher antPathMatcher = new AntPathMatcher();
        for (GrantedAuthority authority : authorities) {
            if (antPathMatcher.match(authority.getAuthority(), (String) permission)) {
                 //说明当前登录的用户具备当前访问所需要的权限
                 return true;
            }
        }

        return false;
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
        return false;
    }
}
